package com.component;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;

import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.tree.base.TreeDataProvider;
import org.operamasks.faces.component.tree.impl.UITree;
import org.operamasks.faces.component.tree.impl.UITreeNode;
import org.operamasks.faces.event.ajax.TreeNodeEvent;
import org.operamasks.faces.user.util.Browser;

import com.base.commons.SpringBeanHolder;
import com.base.organization.entity.CentralUnit;
import com.base.organization.entity.DepartmentalUnit;
import com.base.organization.service.IOrganizationService;
import com.base.security.SecurityConst;
import com.base.utils.DataStructureUtils;

@ManagedBean(name = "component_deptMultiTreeBean", scope = ManagedBeanScope.SESSION)
public class DeptMultiTreeBean implements Serializable {
	private IOrganizationService orgService = SpringBeanHolder
			.getBean("orgService");
	@Inject
	private FacesContext context;
	@Bind(id = "ds_txt", attribute = "value")
	private String ds_txt;
	// 搜索map
	private Map<String, Set<Integer>> searchMap;
	@Bind
	private UITree dm_selectTree;
	@Bind(id = "dm_selectTree")
	private TreeDataProvider treeData_dm_selectTree = new TreeDataProvider() {

		public Object[] getChildren(Object nodeData) {
			// 搜索
			if (ds_txt != null && !"".equals(ds_txt)) {
				if (nodeData == null) {
					return new String[] { "机构" };
				}
				if ("机构".equals(nodeData)) {
					Set<Integer> topUnits = searchMap
							.get(SecurityConst.MAP_KEY_ORG);
					return orgService.getTopCentralUnitByIds(
							DataStructureUtils.setToList(topUnits)).toArray();
				}
				if (nodeData instanceof CentralUnit) {
					Set<Integer> topUnits = searchMap
							.get(SecurityConst.MAP_KEY_ORG);
					CentralUnit cu = (CentralUnit) nodeData;
					List<CentralUnit> units = orgService
							.getDirectChildUnitsByIds(cu.getCentralUnitId(),
									DataStructureUtils.setToList(topUnits));
					// 出机构的部门与机构的下级机构
					List<DepartmentalUnit> deps = orgService
							.getTopDeptOfUnit(cu.getCentralUnitId());
					int depSize = deps.size();
					int unitSize = units.size();
					Object[] result = new Object[depSize + unitSize];
					// 出机构部门
					for (int i = 0; i < depSize; i++) {
						result[i] = deps.get(i);
					}
					// 出子机构
					for (int n = 0; n < unitSize; n++) {
						result[n + depSize] = units.get(n);
					}
					return result;
				}
				if (nodeData instanceof DepartmentalUnit) {
					List<Integer> listDepts = DataStructureUtils
							.setToList(searchMap
									.get(SecurityConst.MAP_KEY_DEPT));
					DepartmentalUnit du = (DepartmentalUnit) nodeData;
					List<DepartmentalUnit> temp = orgService
							.getDirectChildDeptsByIds(du
									.getDepartmentalUnitId(), listDepts);
					// 如果无子部门，直接返回
					if (temp.isEmpty()) {
						return null;
					}
					// 如果有子部门，出子部门
					return temp.toArray();
				}
			} else {
				if (nodeData == null) {
					return new String[] { "机构" };
				}
				if ("机构".equals(nodeData)) {
					return orgService.getTopCentralUnit().toArray();
				}
				if (nodeData instanceof CentralUnit) {
					CentralUnit cu = (CentralUnit) nodeData;
					List<CentralUnit> units = orgService.getDirectChildUnits(cu
							.getCentralUnitId());
					// 出机构的部门与机构的下级机构
					List<DepartmentalUnit> deps = orgService
							.getTopDeptOfUnit(cu.getCentralUnitId());
					int depSize = deps.size();
					int unitSize = units.size();
					Object[] result = new Object[depSize + unitSize];
					// 出机构部门
					for (int i = 0; i < depSize; i++) {
						result[i] = deps.get(i);
					}
					// 出子机构
					for (int n = 0; n < unitSize; n++) {
						result[n + depSize] = units.get(n);
					}
					return result;
				}
				if (nodeData instanceof DepartmentalUnit) {
					DepartmentalUnit du = (DepartmentalUnit) nodeData;
					List<DepartmentalUnit> temp = orgService
							.getDirectChildDepts(du.getDepartmentalUnitId());
					// 如果无子部门，直接返回
					if (temp.isEmpty()) {
						return null;
					}
					// 如果有子部门，出子部门
					return temp.toArray();
				}
			}
			return null;
		}

		public String getHref(Object nodeData) {
			return null;
		}

		public String getHrefTarget(Object nodeData) {
			return null;
		}

		public String getIcon(Object nodeData) {
			if (nodeData instanceof CentralUnit) {
				if (((CentralUnit) nodeData).getParentCentralUnitId() == null)
					return context.getExternalContext().getRequestContextPath()
							+ "/images/topOrg.gif";
				else
					return context.getExternalContext().getRequestContextPath()
							+ "/images/subOrg.gif";
			}
			if (nodeData instanceof DepartmentalUnit) {
				if (((DepartmentalUnit) nodeData).getParentDepartmentalUnitId() == null)
					return context.getExternalContext().getRequestContextPath()
							+ "/images/topDepart.gif";
				else
					return context.getExternalContext().getRequestContextPath()
							+ "/images/subDepart.gif";
			}
			return null;
		}

		public String getText(Object nodeData) {
			if (nodeData == null)
				return null;
			if (nodeData instanceof CentralUnit)
				return ((CentralUnit) nodeData).getName();
			if (nodeData instanceof DepartmentalUnit)
				return ((DepartmentalUnit) nodeData).getName();
			return nodeData.toString();
		}

		public boolean isCascade(Object nodeData) {
			return false;
		}

		public Boolean isChecked(Object nodeData) {
			return null;
		}

		public boolean isExpanded(Object nodeData) {
			if (nodeData == null)
				return false;
			if (ds_txt != null && !"".equals(ds_txt))
				return true;
			if (nodeData instanceof DepartmentalUnit) {
				DepartmentalUnit du = (DepartmentalUnit) nodeData;
				List<DepartmentalUnit> temp = orgService.getDirectChildDepts(du
						.getDepartmentalUnitId());
				// 如果无子部门
				if (temp.isEmpty())
					return true;
			}
			return false;
		}
	};

	@Action(id = "dm_selectTree", event = "onclick")
	public void click(TreeNodeEvent event) {
		UITreeNode node = event.getEventNode();
		Object data = node.getUserData();
		if (data == null)
			return;
		if (data instanceof DepartmentalUnit) {
			DepartmentalUnit du = (DepartmentalUnit) data;
			String script = "addSelected('" + du.getDepartmentalUnitId()
					+ "','" + du.getName() + "')";
			Browser.execClientScript(script);
		}
	}

	@Action(id = "deptSearch")
	public void searchDept() {
		if (ds_txt != null && !"".equals(ds_txt)) {
			searchMap = orgService.getDepMap(ds_txt);
		}
		dm_selectTree.setRootVisible(false);
		dm_selectTree.setAutoScroll(true);
		dm_selectTree.repaint();
	}

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			ds_txt = null;
			searchMap = null;
		}
	}
}
